//
//  CloudDataManager.m
//  OrangeNote
//
//  Created by 刘崇龙 on 16/1/25.
//  Copyright © 2016年 崇龙. All rights reserved.
//

#import "CloudDataManager.h"
#import <AVOSCloud/AVOSCloud.h>
#import "NotebookModel.h"
#import "NoteModel.h"

@implementation CloudDataManager

#pragma mark --- Notebook

// 为用户创建新的笔记本
- (void)insertNotebookWithNotebookModel:(NotebookModel *)notebookModel{
    
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        NSLog(@"Cloud请先登陆!");
        return;
    }
    
    // 名不能为空
    if (notebookModel.name == nil || [notebookModel.name isEqualToString:@""]) {
        NSLog(@"Cloud笔记本名不能为空!");
        return;
    }else{
        
        // 名不能重复
        AVQuery *query = [AVQuery queryWithClassName:@"Notebook"];
        [query whereKey:@"name" equalTo:notebookModel.name];
        
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            if (!error) {
                
                if (objects.count == 0) {
                    
                    AVObject *notebook = [AVObject objectWithClassName:@"Notebook"];
                    notebook[@"name"] = notebookModel.name;
                    notebook[@"ID"] = notebookModel.ID;
                    notebook[@"created"] = notebookModel.createdAt;
                    notebook[@"updated"] = notebookModel.updatedAt;
                    
                    // 为笔记本与用户设置关联
                    [notebook setObject:currentUser forKey:@"userid"];
                    
                    [notebook saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            NSLog(@"Cloud笔记本插入成功!");
                        }else{
                            NSLog(@"Cloud插入失败!%@",error);
                        }
                    }];
                    
                }else{
                    NSLog(@"Cloud不能重名!");
                }
                
            }else{
                NSLog(@"Cloud出错了!!%@",error);
                
            }
        }];
    }
}

// 删除笔记本
- (void)deleteNotebookWithID:(NSString *)ID{
    AVQuery *query = [AVQuery queryWithClassName:@"Notebook"];
    [query whereKey:@"ID" equalTo:ID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                [objects.firstObject deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    
                    if (succeeded) {
                        NSLog(@"Cloud删除成功!");
                    }else{
                        NSLog(@"Cloud删除失败!%@",error);
                    }
                    
                    
                }];
            }else{
                NSLog(@"Cloud未找到数据!");
            }
            
            
        }else{
            NSLog(@"Cloud出错了!!%@",error);
        }
        
    }];
}


// 更改笔记本名称
- (void)updateNotebookNameWithID:(NSString *)ID andNewName:(NSString *)newName{
    AVQuery *query = [AVQuery queryWithClassName:@"Notebook"];
    [query whereKey:@"ID" equalTo:ID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                [objects.firstObject setObject:newName forKey:@"name"];
                
                [objects.firstObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        NSLog(@"Cloud笔记本更改成功!");
                    }else{
                        NSLog(@"Cloud笔记本更改失败!%@",error);
                    }
                }];
            }else{
                NSLog(@"Cloud未找到数据!");
            }
        }else{
            NSLog(@"Cloud出错了!!%@",error);
        }
        
        
    }];
}

// 查询笔记本
- (void)selectNotebookWhereKey:(NSString *)key equalTo:(id)something{
    AVQuery *query = [AVQuery queryWithClassName:@"Notebook"];
    [query whereKey:key equalTo:something];
    [query orderByDescending:@"updated"];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                NSMutableArray *notebookArray = [NSMutableArray arrayWithCapacity:5];
                
                for (AVObject *obj in objects) {
                    NotebookModel *model = [[NotebookModel alloc]init];
                    model.name = obj[@"name"];
                    model.ID = obj[@"ID"];
                    model.createdAt = obj[@"created"];
                    model.updatedAt = obj[@"updated"];
                    [notebookArray addObject:model];
                }
                // 这里是在子线程 无法return  需要传值出去
                self.sendNotebookArray(notebookArray);
            }else{
                NSLog(@"Cloud未找到数据!");
            }
        }else{
            NSLog(@"出错了!!%@",error);
        }
    }];
}


#pragma mark --- note
// 插入笔记
- (void)insertNoteWithNoteModel:(NoteModel *)noteModel andNotebookID:(NSString *)notebookID{
    
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        NSLog(@"清先登陆!");
        return;
    }
    
    // 名不能为空
    if (noteModel.name == nil || [noteModel.name isEqualToString:@""]) {
        noteModel.name = @"未命名笔记";
    }
    
    
    AVObject *note = [AVObject objectWithClassName:@"Note"];
    note[@"name"] = noteModel.name;
    note[@"content"] = noteModel.content;
    note[@"ID"] = noteModel.ID;
    note[@"created"] = noteModel.createdAt;
    note[@"updated"] = noteModel.updatedAt;
    
    
    // img 转 imgData
    NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
    for (UIImage *img in noteModel.imgArray) {
        NSData *imgData = UIImageJPEGRepresentation(img, 1);
        [imgDataArray addObject:imgData];
    }
    
    // imgArray归档
    NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:500];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
    [archiver encodeObject:imgDataArray forKey:[NSString stringWithString:noteModel.ID]];
    [archiver finishEncoding];
    
    AVFile *imgArrayFile = [AVFile fileWithData:imgArrayData];
    
    
    note[@"imgArray"] = imgArrayFile;
    //////////////
    //audioArray//
    //////////////
    note[@"audioArray"] = nil;
    
    // 为笔记与用户设置关联
    [note setObject:currentUser forKey:@"userid"];
    // 为笔记与笔记本设置关联
    [note setObject:notebookID forKey:@"notebookID"];
    
    
    [note saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"Cloud笔记插入成功!");
        }else{
            NSLog(@"出错了!!%@",error);
        }
    }];
}

// 删除笔记
- (void)deleteNoteWithNoteID:(NSString *)ID{
    AVQuery *query = [AVQuery queryWithClassName:@"Note"];
    [query whereKey:@"ID" equalTo:ID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                [objects.firstObject deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    
                    if (succeeded) {
                        NSLog(@"Cloud删除成功!");
                    }else{
                        NSLog(@"Cloud删除失败!%@",error);
                    }
                    
                    
                }];
            }else{
                NSLog(@"Cloud未找到数据!");
            }
            
            
        }else{
            NSLog(@"Cloud出错了!!%@",error);
        }
        
    }];
}

// 更改笔记
- (void)updateNoteWithID:(NSString *)ID andNewNote:(NoteModel *)note{
    AVQuery *query = [AVQuery queryWithClassName:@"Note"];
    [query whereKey:@"ID" equalTo:ID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                [objects.firstObject setObject:note.name forKey:@"name"];
                [objects.firstObject setObject:note.content forKey:@"content"];
                [objects.firstObject setObject:[NSDate dateWithTimeIntervalSinceNow:0] forKey:@"update"];
                
                
                // img 转 imgData
                NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
                for (UIImage *img in note.imgArray) {
                    NSData *imgData = UIImageJPEGRepresentation(img, 1);
                    [imgDataArray addObject:imgData];
                }
                
                // imgArray归档
                NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:500];
                NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
                [archiver encodeObject:imgDataArray forKey:[NSString stringWithString:note.ID]];
                [archiver finishEncoding];
                
                AVFile *imgArrayFile = [AVFile fileWithData:imgArrayData];
                
                
                
                [objects.firstObject setObject:imgArrayFile forKey:@"imgArray"];
                // 录音待增加
                [objects.firstObject setObject:note.audioArray forKey:@"audioArray"];
                
                [objects.firstObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        NSLog(@"Cloud笔记本更改成功!");
                    }else{
                        NSLog(@"Cloud笔记本更改失败!%@",error);
                    }
                }];
            }else{
                NSLog(@"Cloud未找到数据!");
            }
        }else{
            NSLog(@"Cloud出错了!!%@",error);
        }
        
        
    }];
}

// 查询笔记
- (void)selectNoteWhereKey:(NSString *)key equalTo:(id)something{
    AVQuery *query = [AVQuery queryWithClassName:@"Note"];
    [query whereKey:key equalTo:something];
    [query orderByDescending:@"updated"];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            
            if (objects.count != 0) {
                NSMutableArray *noteArray = [NSMutableArray arrayWithCapacity:5];
                
                for (AVObject *obj in objects) {
                    NoteModel *model = [[NoteModel alloc]init];
                    model.name = obj[@"name"];
                    model.ID = obj[@"ID"];
                    model.createdAt = obj[@"created"];
                    model.updatedAt = obj[@"updated"];
                    model.content = obj[@"content"];
                    
                    
                    NSData *imgArrayData = [obj[@"imgArray"] getData];
                    
                    // imgArray反归档
                    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:imgArrayData];
                    NSMutableArray *imgDataArray = [unarchiver decodeObjectForKey:model.ID];
                    [unarchiver finishDecoding];
                    
                    // imgData 转 img
                    NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:5];
                    for (NSData *data in imgDataArray) {
                        UIImage *img = [UIImage imageWithData:data];
                        [imgArray addObject:img];
                    }
                    
                    
                    //                    for (AVFile *imgFile in obj[@"imgArray"]) {
                    //                        NSData *imgData = [imgFile getData];
                    //                        UIImage *img = [UIImage imageWithData:imgData];
                    //                        [imgArray addObject:img];
                    //                    }
                    model.imgArray = imgArray;
                    model.audioArray = [NSMutableArray array];
                    
                    [noteArray addObject:model];
                }
                // 这里是在子线程 无法return  需要传值出去
                self.sendNoteArray(noteArray);
            }else{
                NSLog(@"Cloud未找到数据!");
            }
        }else{
            NSLog(@"出错了!!%@",error);
        }
    }];
}




@end
